//
//  OriginalMapViewController.m
//  GNAPP
//
//  Created by zzp on 2019/1/9.
//  Copyright © 2019年 zzp. All rights reserved.
//

#import "OriginalMapViewController.h"
#import <MapKit/MapKit.h>
#import "WPAnnotation.h"
#import <CoreLocation/CoreLocation.h>
#import <FMDB/FMDB.h>
#import "Location.h"

@interface OriginalMapViewController ()<MKMapViewDelegate>

@property(nonatomic,strong) CLLocationManager *locMgr;
@property (strong, nonatomic)  MKMapView *mapView;
@property (nonatomic, strong) NSMutableArray *annotations;
@property (nonatomic,strong)  MKAnnotationView *currentAnnotationView;
//编码工具
@property(strong,nonatomic)CLGeocoder *geocoder;


//用于发送请求给服务器
@property(strong,nonatomic)MKDirections *direct;

@end

@implementation OriginalMapViewController

-(CLLocationManager *)locMgr{
    if (_locMgr==nil) {
        _locMgr=[[CLLocationManager alloc]init];
    }
    return _locMgr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([[UIDevice currentDevice].systemVersion doubleValue]>=8.0) {
        [self.locMgr requestWhenInUseAuthorization];
    }
    //初始化地图控件。与根视图保持一致
    self.mapView = [[MKMapView alloc]initWithFrame:self.view.bounds];
    //显示当前用户的地理位置
    self.mapView.showsUserLocation = true;
    [self.view addSubview:self.mapView];
    //显示用户位置（蓝色发光圆圈），还有None和FollowWithHeading两种，当有这个属性的时候，iOS8第一次打开地图，会自动定位并显示这个位置。iOS7模拟器上不会。
    self.mapView.userTrackingMode=MKUserTrackingModeFollow;
    
    //地图模式，默认是standard模式，还有卫星模式satellite和杂交模式Hybrid
    self.mapView.mapType=MKMapTypeStandard;
    
    //设置代理
    self.mapView.delegate=self;
    
    [self initAnnotations];
//    WPAnnotation *anno1=[[WPAnnotation alloc]init];
//    anno1.coordinate=CLLocationCoordinate2DMake(39, 115);
//    anno1.title=@"万达影院";
//    anno1.subtitle=@"全中国最顶尖的观影圣地";
//    anno1.icon=@"guangqi.jpg";
//    [self.mapView addAnnotation:anno1];
    

    [self.mapView addAnnotations:self.annotations];
//    [self.mapView showAnnotations:self.annotations animated:YES];
//    [self addStartAndEnd];
//    [self startNavigation];
//       [self.mapView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMapView:)]];
}

/**
 *  开始导航
 */
- (void)startNavigation{
    //1,获取用户输入的起点终点
    
    //2,利用GEO对象进行地理编码获取地标对象
    
    CLLocationCoordinate2D coords = CLLocationCoordinate2DMake([Location shareLocation].latitude, [Location shareLocation].longtitude);
    CLLocation * currentLocation = [[CLLocation alloc]initWithLatitude:coords.latitude longitude:coords.longitude];
    if(!_geocoder){
        //   提供两个点，自动规划线路
        _geocoder = [[CLGeocoder alloc]init];
    }
    //2.1 获取开始位置的地标
    [self.geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count ==0 ||error != nil) {
            
            return ;
        }
        //开始位置的地标
        CLPlacemark * startPlacemark = [placemarks firstObject];
        
        //3,获得结束位置的地标
        float latitude = self.currentAnnotationView.annotation.coordinate.latitude;
        float longitude = self.currentAnnotationView.annotation.coordinate.longitude;
        CLLocationCoordinate2D coords1 = CLLocationCoordinate2DMake(latitude,longitude);
        CLLocation * currentLocation1 = [[CLLocation alloc]initWithLatitude:coords1.latitude longitude:coords1.longitude];
        [self.geocoder reverseGeocodeLocation:currentLocation1 completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (placemarks.count ==0 ||error != nil) {

                return ;
            }
            CLPlacemark * endPlacemark = [placemarks firstObject];
            //4,获得地标后开始导航
            //destItem可以理解为地图上的一个点
            MKMapItem *destItem = [[MKMapItem alloc]initWithPlacemark:[[MKPlacemark alloc]initWithPlacemark:endPlacemark]];
             MKMapItem *startItem = [[MKMapItem alloc]initWithPlacemark:[[MKPlacemark alloc]initWithPlacemark:startPlacemark]];
            
            [self moveWith:startItem toDestination:destItem];
        }];
        
    }];
}
-(void)addStartAndEnd{
    //   提供两个点，自动规划线路
    _geocoder = [[CLGeocoder alloc]init];
    
    [_geocoder geocodeAddressString:@"广东省广州市番禺区墟心街靠近茭塘西村幼儿园" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        
        MKPlacemark *placemark = [[MKPlacemark alloc]initWithPlacemark:placemarks.lastObject];
        //intrItem可以理解为地图上的一个点
        MKMapItem *intrItem = [[MKMapItem alloc]initWithPlacemark:placemark];
        
        //        添加一个小别针到地图上
        WPAnnotation *anno = [[WPAnnotation alloc]init];
        anno.coordinate = intrItem.placemark.location.coordinate;
        [self.mapView addAnnotation:anno];
        
        // 让地图跳转到起点所在的区域
        MKCoordinateRegion region = MKCoordinateRegionMake(intrItem.placemark.location.coordinate, MKCoordinateSpanMake(0.1, 0.1));
        [self.mapView setRegion:region];
        
        //创建终点
        [self->_geocoder geocodeAddressString:@"深圳北站" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            
            //destItem可以理解为地图上的一个点
            MKMapItem *destItem = [[MKMapItem alloc]initWithPlacemark:[[MKPlacemark alloc]initWithPlacemark:[placemarks lastObject]]];
            
            
            //        添加一个小别针到地图上
            WPAnnotation *anno = [[WPAnnotation alloc]init];
            anno.coordinate = destItem.placemark.location.coordinate;
            [self.mapView addAnnotation:anno];
            
            //调用下面方法发送请求
            [self moveWith:intrItem toDestination:destItem];
        }];
    }];
}
//提供两个点，在地图上进行规划的方法
-(void)moveWith:(MKMapItem *)formPlce toDestination:(MKMapItem *)endPlace{
    
    //    创建请求体
    // 创建请求体 (起点与终点)
    MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
    
    request.source = formPlce;
    request.destination = endPlace;
    
    self.direct = [[MKDirections alloc]initWithRequest:request];
    
    // 计算路线规划信息 (向服务器发请求)
    [self.direct calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse * _Nullable response, NSError * _Nullable error) {
        
        //获取到所有路线
        NSArray <MKRoute *> *routesArray = response.routes;
        //取出最后一条路线
        MKRoute *rute = routesArray.lastObject;
        
        //路线中的每一步
        NSArray <MKRouteStep *>*stepsArray = rute.steps;
        
        //遍历
        for (MKRouteStep *step in stepsArray) {
            
            [self.mapView addOverlay:step.polyline];
        }
        // 收响应结果 MKDirectionsResponse
        // MKRoute 表示的一条完整的路线信息 (从起点到终点) (包含多个步骤)
    }];
    
}
- (void)initAnnotations
{
    self.annotations = [NSMutableArray array];
    
    //1.获得数据库文件的路径
    
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [path objectAtIndex:0];
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MAP" ofType:@"db"];
    NSString *dstPath = [docDirectory stringByAppendingPathComponent:@"MAP.db"];
    NSLog(@"%@",filePath);
    if(![[NSFileManager defaultManager]fileExistsAtPath:dstPath]){
        [[NSFileManager defaultManager] copyItemAtPath:filePath toPath:dstPath error:nil];
    }
    //2.获得数据库
    FMDatabase *db=[FMDatabase databaseWithPath:dstPath];
    
    int count=0;
    //3.打开数据库
    if ([db open]) {
        // 1.执行查询语句
        FMResultSet *resultSet = [db executeQuery:@"select field_3, field_12 , field_13 from bb  "];
        FMResultSet *countSet = [db executeQuery:@"select count(*) as aa from bb"];
        
        if([countSet next]){
            count=[countSet intForColumn:@"aa"];
        }
        
        CLLocationCoordinate2D coordinates[count];
        int index=0;
        // 2.遍历结果
        while ([resultSet next]) {
            double  longitude= [resultSet doubleForColumn:@"field_12"];
            double latitude = [resultSet doubleForColumn:@"field_13"];
            NSString * name = [resultSet stringForColumn:@"field_3"];
            CLLocationCoordinate2D newCoordinate =CLLocationCoordinate2DMake(latitude,longitude);
            coordinates[index]=newCoordinate;
            index++;
//            MKPointAnnotation *a1 = [[MKPointAnnotation alloc] init];
//            a1.coordinate = newCoordinate;
//            a1.title      = name;
            
            WPAnnotation *a1=[[WPAnnotation alloc]init];
            a1.coordinate=newCoordinate;
            a1.title=name;
            a1.icon=@"img_map_marker";
            [self.annotations addObject:a1];
            //              NSLog(@"resultSet %lf  %lf", ID, name);
        }
        
        
    }else{
        
        
    }
}
#pragma mark MapView Delegate

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    static NSString *ID=@"annoView";
    MKAnnotationView *annoView=[mapView dequeueReusableAnnotationViewWithIdentifier:ID];
    if (annoView==nil) {
        annoView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:ID];
        //点击大头针出现信息（自定义view的大头针默认点击不弹出）
        annoView.canShowCallout=YES;
    }
    //再传递一次annotation模型（赋值）
    annoView.annotation=annotation;
    if([annotation isKindOfClass:[WPAnnotation class]]){
        WPAnnotation *anno=annotation;
        annoView.image=[UIImage imageNamed:anno.icon];
    }else{
        annoView.image=[UIImage imageNamed:@"userPosition"];
    }

    return annoView;
}
//-(void)tapMapView:(UITapGestureRecognizer *)tap{
//    //获取点击的点
//    CGPoint point=[tap locationInView:tap.view];
//    //点转换成坐标
//    CLLocationCoordinate2D coordi=[self.mapView convertPoint:point toCoordinateFromView:self.mapView];
//    //创建大头针模型，设置大头针的坐标，然后把大头针加进去
//    MKAnnotationView *anno=[[MKAnnotationView alloc]init];
//
//
//    MKPointAnnotation *a1 = [[MKPointAnnotation alloc] init];
//    a1.coordinate = coordi;
////    a1.title      = name;
////    anno.coordinate=coordi;
//    a1.title=@"拙政园";
//    a1.subtitle=@"苏州市博物馆附近";
//    anno.annotation=a1;
//    [self.mapView addAnnotation:anno];
//}

//MKUserLocation是地图上大头针模型，有title和subtitle以及location信息。该方法调用频繁
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    NSLog(@"%f,%f",userLocation.location.coordinate.longitude,userLocation.location.coordinate.latitude);
    //点击大头针，会出现以下信息
    userLocation.title=@"中国";
    userLocation.subtitle=@"四大文明古国之一";

    //让地图显示用户的位置（iOS8一打开地图会默认转到用户所在位置的地图），该方法不能设置地图精度
    //    [mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];

    //这个方法可以设置地图精度以及显示用户所在位置的地图
    MKCoordinateSpan span=MKCoordinateSpanMake(0.1, 0.1);
    MKCoordinateRegion region=MKCoordinateRegionMake(userLocation.location.coordinate, span);
    [mapView setRegion:region animated:YES];
}

//可以打印经纬度的跨度，用来测试当前视图下地经纬度跨度是多少，然后用于上面的MKCoordinateSpanMake方法中
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    NSLog(@"%f,%f",mapView.region.span.latitudeDelta,mapView.region.span.longitudeDelta);
}

-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{
    NSLog(@"view.annotation.title %@",view.annotation.title);
    self.currentAnnotationView=view;
    [self startNavigation];
}
// 返回指定的遮盖模型所对应的遮盖视图, renderer-渲染
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
    // 判断类型
    if ([overlay isKindOfClass:[MKPolyline class]]) {
        // 针对线段, 系统有提供好的遮盖视图
        MKPolylineRenderer *render = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
        
        // 配置，遮盖线的颜色
        render.lineWidth = 5;
        render.strokeColor =  [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1.0];
        
        return render;
    }
    // 返回nil, 是没有默认效果
    return nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
